<?php

namespace App\Admin\Controllers;

use App\Exceptions\BizException;
use App\RiskRule;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\MessageBag;

class RiskRuleController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '规则列表';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new RiskRule());

        $grid->model()->orderByDesc('id');
        $grid->expandFilter();

        $grid->filter(function (Grid\Filter $filter) {

            $filter->disableIdFilter();

            $filter->column(1/2, function(Grid\Filter $filter){
                $filter->equal('id', 'ID');
                $filter->equal('thqzdj', '团伙欺诈');
                $filter->contains('gzmc', __('Gzmc'));


            });
            $filter->column(1/2, function(Grid\Filter $filter){

                $filter->equal('dengji', '等级')->select(RiskRule::DENGJI_MAP);
                $filter->contains('name', __('Name'));
            });
        });


        $grid->column('id', __('Id'));
        $grid->column('dengji', __('Dengji'))->using(RiskRule::DENGJI_MAP);
        $grid->column('gzmc', __('Gzmc'));
        $grid->column('money', __('Money'));
        $grid->column('status', '状态')->switch([
            'on'  => ['value' => 0, 'text' => '启用', 'color' => 'primary'],
            'off' => ['value' => 1, 'text' => '停用', 'color' => 'danger'],
        ]);
        $grid->column('age', __('Age'))->hide();
        $grid->column('name', __('Name'))->limit(80);

        $grid->column('courtdetail', __('Courtdetail'))->hide();
        $grid->column('c3', __('C3'))->hide();
        $grid->column('zxf', __('Zxf'))->hide();
        $grid->column('zzf', __('Zzf'))->hide();
        $grid->column('thqzdj', __('Thqzdj'))->hide();
        $grid->column('jdyxyz', __('Jdyxyz'))->hide();
        $grid->column('fxsb', __('Fxsb'))->hide();
        $grid->column('tsmdyz', __('Tsmdyz'))->hide();
        $grid->column('fybzxr', __('Fybzxr'))->hide();

        $grid->column('sort', __('Sort'));
        $grid->column('z_name', __('Z name'))->hide();
        $grid->column('ady', __('Ady'))->hide();
        $grid->column('ultimately', __('Ultimately'))->hide();
        $grid->column('created_at', __('Created at'));
        $grid->column('updated_at', __('Updated at'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(RiskRule::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('dengji', __('Dengji'));
        $show->field('gzmc', __('Gzmc'));
        $show->field('money', __('Money'));
        $show->field('age', __('Age'));
        $show->field('courtdetail', __('Courtdetail'));
        $show->field('c3', __('C3'));
        $show->field('zxf', __('Zxf'));
        $show->field('zzf', __('Zzf'));
        $show->field('thqzdj', __('Thqzdj'));
        $show->field('jdyxyz', __('Jdyxyz'));
        $show->field('fxsb', __('Fxsb'));
        $show->field('tsmdyz', __('Tsmdyz'));
        $show->field('fybzxr', __('Fybzxr'));
        $show->field('name', __('Name'));
        $show->field('sort', __('Sort'));
        $show->field('z_name', __('Z name'));
        $show->field('ady', __('Ady'));
        $show->field('ultimately', __('Ultimately'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new RiskRule());

        $form->saving(function (Form $form) {
            //保存前回掉

            //获取提交数据
            $data = \request()->input();


            try{

                if(!empty($data['gzmc'])){
                    $result = RiskRule::conversionData($data);
                    if(!$result['status']){
                        throw new BizException($result['msg']);
                    }
                    foreach ($data as $key => $val){
                        if(!empty($val) && strpos($val,' ') !== false){
//                            throw new BizException('7777777777');
                            $form->$key = str_replace(" ","",$val);
                        }
                    }

                    //追加保存字段
                    $form->model()->z_name = $result['z_name'];
                    $form->model()->ultimately = json_encode($result['arr']);

                    \Log::channel('push_pv')->info('规则列:',[$data,$result]);
                }


//                throw new BizException(json_encode($result['arr']));
            }catch (\Exception $e){

                $error = new MessageBag([
                    'title'   => '错误',
                    'message' => $e->getMessage(),
                ]);
                \Log::channel('push_pv')->info('push_order_id:',[$data]);
                return back()->with(compact('error'));
            }

        });

        $form->saved(function (Form $form) {
            //保存后回掉
            Redis::del('rule_list');
        });

        $form->select('dengji','等级')->rules('required')->default(1)->options(RiskRule::DENGJI_MAP);
        $form->text('gzmc','规则名称')
            ->creationRules(['required', "unique:risk_rules"], ['required' => '规则名称不能为空','unique' => '规则名称不能重复'])
            ->updateRules(['required', "unique:risk_rules,gzmc,{{id}}"],['required' => '规则名称不能为空','unique' => '规则名称不能重复'])
            ->required();
        ;


        $form->text('name','名称');
        $form->switch('status', '状态')->states([
            'on'  => ['value' => 0, 'text' => '启用', 'color' => 'primary'],
            'off' => ['value' => 1, 'text' => '停用', 'color' => 'danger'],
        ]);

        $form->text('money','金额限制')->default('')->help("金额限制在2000-4000只需填写:2000-4000 金额大于7000填:>,7000 其他符号有>,>=,==,-,<,");
        $form->text('age','年龄限制');

        $form->text('courtdetail','法院信息详情-个人高级版')
            ->help('例子失信被执行人身份证+匹配度≥0.65: shixin,>=,0.65 (失信被执行人:shixin 执行公告被执行人:zxgg 法院公告:fygg 曝光台:bgt 网贷黑名单:wdhmd)');

        $form->text('c3','3C申请意向-3C租赁')
            ->help('身份证/按手机号查询，近3个月在3C机构申请总次数≥9次:m3.id.allnum,>=,9&m3.cell.allnum,>=,9 数据解析 时间.查询类型.数据类型');

        $form->text('zxf','租信分');
        $form->text('zzf','租智分');
        $form->text('thqzdj','团伙欺诈等级');
        $form->text('jdyxyz','借贷意向验证')->help('近15天在非银机构申请次数 >= 10:d15.id.nbank.allnum,>=,10  银行机构:bank 非银机构:nbank');
        $form->text('fxsb','风险哨兵')->help('风险哨兵90以上（三个维度均满足趋势异常,消费行为预测,履约意愿）:qsyc,>=,90&xfxwyc,>=,90&lyyy,>=,90');
        $form->text('tsmdyz','反欺诈-特殊名单验证')->help('输入类型编号例如:odr0000342');
        $form->text('tsmd','特殊名单验证')->help('按身份证查询:id.nbank_finlea_bad_time,>=,1,按手机号查询:cell.nbank_finlea_bad_time,>=,1 ****注意：查询方式.类型 ********只有一个点！！！');
        $form->text('fybzxr','反欺诈规则-法院被执行人限高版')->help('输入类型编号例如:odr0000210');
        $form->text('czylzs','偿债压力指数');
        $form->text('ady','自定义')->help('特殊情况可以再这儿输入');
        $form->number('sort','排序')->default(10000)->help('越小越靠前');

        $form->textarea('ultimately','最终综合条件')->disable();




//        $form->number('dengji', __('Dengji'));
//        $form->text('gzmc', __('Gzmc'));
//        $form->text('money', __('Money'));
//        $form->text('age', __('Age'));
//        $form->text('courtdetail', __('Courtdetail'));
//        $form->text('c3', __('C3'));
//        $form->text('zxf', __('Zxf'));
//        $form->text('zzf', __('Zzf'));
//        $form->text('thqzdj', __('Thqzdj'));
//        $form->text('jdyxyz', __('Jdyxyz'));
//        $form->text('fxsb', __('Fxsb'));
//        $form->text('tsmdyz', __('Tsmdyz'));
//        $form->text('fybzxr', __('Fybzxr'));
//        $form->text('name', __('Name'));
//        $form->number('sort', __('Sort'))->default(10000);
//        $form->text('z_name', __('Z name'));
//        $form->text('ady', __('Ady'));
//        $form->textarea('ultimately', __('Ultimately'));

        return $form;
    }
}
